package edu.cuit.campus.commons;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;

import java.io.IOException;
import java.util.Properties;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/7 16:13
 */
@Slf4j
public class MailSender {
    private static String host;
    private static String from;
    private static String code;
    private static int port = 465;
    private MailSender(){

    }

    static{
        try {
            var input = MailSender.class.getClassLoader().getResourceAsStream("email.properties");
            var prop = new Properties();
            prop.load(input);
            host = prop.getProperty("mail.host");
            from = prop.getProperty("mail.from");
            code = prop.getProperty("mail.code");
            port = Integer.parseInt(prop.getProperty("mail.port"));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
    public static void sendSimpleEmail(String subject, String content, String... destination){
        try {
            var email = new SimpleEmail();
            //设置发送邮件服务主机 smtp
            email.setHostName(host);
            //smtp协议的端口,默认为465
            email.setSmtpPort(port);
            //认证
            email.setAuthenticator(new DefaultAuthenticator(from, code));
            //使用安全连接SSL进行邮件发送
            email.setSSLOnConnect(true);
            //设置字符编码
            email.setCharset("utf-8");
            //发件箱
            email.setFrom(from);
            //邮件主题
            email.setSubject(subject);
            //邮件内容
            email.setMsg(content);
            //收件人
            email.addTo(destination);
            //邮件发送
            email.send();
        } catch (EmailException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送html格式邮件
     * @param subject 主题
     * @param html html文档内容
     * @param alias 发件人别名
     * @param destination 收件人列表
     */
    public static void sendHtmlEmail(String subject, String html, String alias, String... destination){
        try {
            var email = new HtmlEmail();
            email.setHostName(host);
            email.setAuthenticator(new DefaultAuthenticator(from, code));
            email.setSSLOnConnect(true);
            email.setCharset("utf-8");
            email.addTo(destination);
            email.setFrom(from, alias);
            email.setSubject(subject);
            // set the html message
            email.setHtmlMsg(html);
            // send the email
            email.send();
        } catch (EmailException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
